package eva.savant.business.ventas.view

import eva.savant.businessobject.vt.Cliente
import eva.savant.businessobject.vt.Venta
import groovy.time.TimeCategory

import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped
import javax.annotation.PostConstruct
import javax.faces.convert.Converter

@SessionScoped
@ManagedBean(name = 'IIVentasFrecuencia')
public class IIVentasFrecuencia extends Bean {

  def week, cliente, promedioD= 0, promedioV= 0

  Date dateIni, dateEnd

  @PostConstruct
  public void cleanEntity() {

    week= [ 0,0,0,0,0,0,0 ]

    promedioD= promedioV= 0

    cliente= new Cliente()

    lsEntity= new ArrayList()

    dateIni = dateEnd= new Date()
  }

  public List findLsEntity() {

    week= [ 0,0,0,0,0,0,0 ]; promedioD= promedioV= 0; lsEntity= new ArrayList()

    def ls= find(Venta,'fecha, total: cliente.id=? and fecha between ? and ? order by fecha',cliente.id,dateIni,toMidnight(dateEnd))


    def old= new Date(); for(int i=0; i<ls.size(); i++){ Date d= ls[i][0];  if(i==0) old= d

    def dias= TimeCategory.minus(toStartDay((Date)d),toStartDay(old)).days, total= ls[i][1]

    promedioD= promedioD + dias; def res= [old,d,dias,total]; old= d

    promedioV= promedioV + total


    def dia= d.toCalendar().get(Calendar.DAY_OF_WEEK) - 1

    week[dia] = week[dia] + 1

    lsEntity.add res }


    promedioD= ls.size() > 1? promedioD / (ls.size()-1) : 0

    promedioV= promedioV / ls.size()

    return lsEntity
  }

  public List complete(String value) { return completeLike(Cliente.class,'persona.nombre',value) }

  public Converter getConverter() { return converterLike(Cliente.class) }
}

